import Authorized from '@/utils/Authorized';
import { showMessage } from '@/utils/utils';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Popconfirm,Dropdown, Menu } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType, ColumnsState } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import PermissionCreateForm from './components/permissionCreateForm';
import PermissionUpdateForm, { FormValueType } from './components/permissionUpdateForm';
import { PermissionTableListItem } from './permissionData.d';
import { queryPermission, updatePermission, addPermission, removePermission, removeBatchPermission, updatePermissionButtons } from './permissionService';
import PermissionButtonForm from './components/permissionButtonForm';

/**
 * 添加权限
 * @param fields
 */
const handleAdd = async (fields: PermissionTableListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addPermission({ ...fields }).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

/**
 * 更新权限
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在保存');
    try {
        await updatePermission(fields).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('保存失败请重试！');
        return false;
    }
};
const handleUpdateButtons = async (values: {
    parentId: string,
    buttonPermissions: string[]
}) => {
    const hide = message.loading('正在保存');
    try {
        await updatePermissionButtons(values).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('保存失败请重试！');
        return false;
    }
};

/**
 *  批量删除权限
 * @param selectedRows
 */
const handleRemove = async (selectedRows: PermissionTableListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        await removeBatchPermission({
            ids: selectedRows.map((row) => row.permissionId),
        }).then(res=>{
            showMessage(res);
        });
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

/**
 *  删除权限
 * @param selectedRows
 */
const handleDelete = async (selectedRows: PermissionTableListItem|PermissionTableListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        if(selectedRows instanceof Array){
            await removeBatchPermission({
                ids: selectedRows.map((row) => row.permissionId),
            }).then(res=>{
                showMessage(res);
            });
        }else{
            await removePermission({
                id: selectedRows.permissionId,
            }).then(res=>{
                showMessage(res);
            });
        }
        hide();
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

/**
 * 更多菜单
 */
const handleOtherMenu = async (item: PermissionTableListItem) => {
    return item;
}

const PermissionTableList: React.FC<{}> = () => {
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [buttonModalVisible, handleButtonModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [row, setRow] = useState<PermissionTableListItem>();
    const [currentData, setCurrentData] = useState<PermissionTableListItem>({});
    const [selectedRowsState, setSelectedRows] = useState<PermissionTableListItem[]>([]);
    const [buttonCheckedList, setButtonCheckedList] = useState<[]>([]);
    const columns: ProColumns<PermissionTableListItem>[] = [
        {
            title: '主键',
            key: 'permissionId',
            dataIndex: 'permissionId',
            valueType: 'text',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '父级权限id',
            key: 'parentId',
            dataIndex: 'parentId',
            valueType: 'text',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '权限名称',
            key: 'permissionName',
            dataIndex: 'permissionName',
            valueType: 'text',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '权限名称为必填项',
                    },
                ],
            },
            render: (dom, entity) => {
                return <a onClick={() => setRow(entity)}>{dom}</a>;
            },
        },
        {
            title: '权限',
            key: 'authority',
            dataIndex: 'authority',
            valueType: 'text',
        },
        {
            title: '图标',
            key: 'icon',
            dataIndex: 'icon',
            valueType: 'text',
        },
        {
            title: '权限类型',
            key: 'permissionType',
            dataIndex: 'permissionType',
            filters: true,
            valueEnum: {
                0: { text: '目录', status: 'Default' },
                1: { text: '菜单', status: 'Default' },
                2: { text: '按钮', status: 'Default' },
            },
        },
        {
            title: '路由路径',
            key: 'routePath',
            dataIndex: 'routePath',
            valueType: 'text',
        },
        {
            title: '组件路径',
            key: 'component',
            dataIndex: 'component',
            valueType: 'text',
        },
        {
            title: '外部链接',
            key: 'isOuter',
            dataIndex: 'isOuter',
            filters: true,
            valueEnum: {
                0: { text: '否', status: 'Default' },
                1: { text: '是', status: 'Default' },
            },
        },
        {
            title: '排序',
            key: 'sort',
            dataIndex: 'sort',
            valueType: 'digit',
        },
        {
            title: '状态:',
            key: 'status',
            dataIndex: 'status',
            filters: true,
            valueEnum: {
                0: { text: '禁用', status: 'Default' },
                1: { text: '启用', status: 'Success' },
            },
        },
        {
            title: '备注',
            key: 'remark',
            dataIndex: 'remark',
            valueType: 'text',
            ellipsis: true,
            copyable: true,
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInForm: true,
            search: false,
        },
        {
            title: '创建者',
            key: 'creator',
            dataIndex: 'creator',
            valueType: 'text',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '更新时间',
            key: 'updateTime',
            dataIndex: 'updateTime',
            valueType: 'dateTime',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '修改者',
            key: 'modifier',
            dataIndex: 'modifier',
            valueType: 'text',
            hideInTable: true,
            hideInForm: true,
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <Authorized authority={['admin', 'ums:permission:edit']} noMatch="">
                        <a
                            onClick={() => {
                                handleUpdateModalVisible(true);
                                setCurrentData(record);
                            }}
                        >
                            编辑
                        </a>
                    </Authorized>
                    <Authorized authority={['admin', 'ums:permission:delete']} noMatch="">
                        <Divider type="vertical" />
                        <Popconfirm
                            title="确定要删除?"
                            onConfirm={async ()=>{
                                await handleDelete(record)
                                actionRef.current?.reloadAndRest?.();
                            }}
                        >
                            <a href="#">删除</a>
                        </Popconfirm>
                    </Authorized>
                    <Authorized authority={['admin', 'ums:permission:edit']} noMatch="">
                        <Divider type="vertical" />
                        <Dropdown overlay={
                            <Menu>
                                {record.permissionType!==2 && <Menu.Item>
                                    <a onClick={() => {
                                        setCurrentData(record);
                                        handleModalVisible(true);
                                    }}>
                                        新建
                                    </a>
                                </Menu.Item>}
                                {record.permissionType===1 && (<Menu.Item>
                                    <a onClick={() => {
                                        handleButtonModalVisible(true);
                                        setCurrentData(record);
                                    }}>
                                        按钮
                                    </a>
                                </Menu.Item>)}
                                <Menu.Item>
                                    <a onClick={() => {
                                        handleOtherMenu(record);
                                    }}>
                                        其他
                                    </a>
                                </Menu.Item>
                            </Menu>
                        }>
                            <a>
                                更多 <DownOutlined />
                            </a>
                        </Dropdown>
                    </Authorized>
                </>
            ),
        }
    ];
    const [columnsStateMap, setColumnsStateMap] = useState<{
        [key: string]: ColumnsState;
    }>({
        permissionId: {
            show: true,
        },
        parentId: {
            show: true,
        },
        permissionName: {
            show: true,
        },
        authority: {
            show: true,
        },
        icon: {
            show: true,
        },
        permissionType: {
            show: true,
        },
        routePath: {
            show: true,
        },
        component: {
            show: true,
        },
        isOuter: {
            show: true,
        },
        sort: {
            show: true,
        },
        status: {
            show: false,
        },
        remark: {
            show: false,
        },
        deleteStatus: {
            show: true,
        },
        createTime: {
            show: false,
        },
        creator: {
            show: true,
        },
        updateTime: {
            show: true,
        },
        modifier: {
            show: true,
        },
    });

    return (
        <PageContainer>
            <ProTable<PermissionTableListItem>
                headerTitle="权限"
                actionRef={actionRef}
                rowKey="permissionId"
                search={{
                    labelWidth: 120,
                }}
                scroll={{ x: 1200 }}
                toolBarRender={() => [
                    <Authorized key="auth-add-permissionId" authority={['admin','ums:permission:add']} noMatch=''>
                        <Button type="primary" onClick={() => {
                            setCurrentData({});
                            handleModalVisible(true);
                            }}>
                            <PlusOutlined /> 新建
                        </Button>,
                    </Authorized>
                ]}
                request={(params, sorter, filter) => queryPermission({ ...params, sorter, filter })}
                columns={columns}
                columnsStateMap={columnsStateMap}
                onColumnsStateChange={(map) => setColumnsStateMap(map)}
                rowSelection={{
                    onChange: (_, selectedRows) => setSelectedRows(selectedRows),
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>
                    <Button type="primary">批量操作</Button>
                </FooterToolbar>
            )}
            {/* const title = `111 ${parent?.permissionName||''}`; */}
            <PermissionCreateForm onCancel={() => handleModalVisible(false)}
                modalVisible={createModalVisible}
                title={`新建权限 [父权限: ${ currentData?.permissionName||''}]`}>
                <ProTable<PermissionTableListItem, PermissionTableListItem>
                    onSubmit={async (value) => {
                        let parentId = '0';
                        if(currentData && currentData.permissionId){
                            parentId = currentData.permissionId||'0';
                        }
                        const data = {...value, parentId}
                        console.log('data',data)
                        const success = await handleAdd(data);
                        if (success) {
                            handleModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    rowKey="permissionId"
                    type="form"
                    columns={columns}
                />
            </PermissionCreateForm>
            <PermissionUpdateForm
                onSubmit={async (value: PermissionTableListItem) => {
                    console.log('PermissionUpdateForm onSubmit',value);
                    const success = await handleUpdate(value);
                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentData({});
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleUpdateModalVisible(false);
                    setCurrentData({});
                }}
                updateModalVisible={updateModalVisible}
                currentData={currentData}
            />
            <PermissionButtonForm
                onSubmit={async (value:string[]) => {
                    console.log('PermissionButtonForm onSubmit',value);
                    const data = {
                        parentId: currentData.permissionId||'',
                        buttonPermissions: value
                    }
                    const success = await handleUpdateButtons(data);
                    if (success) {
                        handleButtonModalVisible(false);
                        setCurrentData({});
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleButtonModalVisible(false);
                    setCurrentData({});
                }}
                buttonModalVisible={buttonModalVisible}
                checkedList={buttonCheckedList}
                currentData={currentData}
            />


            <Drawer
                width={600}
                visible={!!row}
                onClose={() => {
                    setRow(undefined);
                }}
                closable={false}
            >
                {row?.permissionName && (
                    <ProDescriptions<PermissionTableListItem>
                        column={2}
                        title={row?.permissionName}
                        request={async () => ({
                            data: row || {},
                        })}
                        params={{
                            id: row?.permissionName,
                        }}
                        columns={columns}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default PermissionTableList;
